import { defineStore, createPinia } from 'pinia'
import { GlobalState, ThemeConfigProps } from './interface'
import { THEME_CONFIG } from '@/config/config'
import piniaPersistConfig from '@/config/piniaPersist'
import { createPersistedState } from 'pinia-plugin-persistedstate'

// defineStore 调用后返回一个函数，调用该函数获得 Store 实体
export const GlobalStore = defineStore({
	// id: 必须的，在所有 Store 中唯一
	id: 'GlobalState',
	// state: 返回对象的函数
	state: (): GlobalState => ({
		// token
		token: '',
		// userInfo
		userInfo: '',
		// element组件大小
		assemblySize: 'default',
		// language
		language: '',
		// themeConfig
		themeConfig: { ...THEME_CONFIG }
	}),
	getters: {
		// 侧栏反转颜色
		sideBgColorGet: state => (state.themeConfig.isDark || state.themeConfig.sideBgRevert ? 'rgb(47, 51, 73)' : '#ffffff'),
		sideTextColorGet: state => (state.themeConfig.isDark || state.themeConfig.sideBgRevert ? '#bdbdc0' : '#303133'),
		headerBgColorGet: state => (state.themeConfig.isDark || state.themeConfig.headerBgRevert ? 'rgb(47, 51, 73)' : '#ffffff'),
		headerTextColorGet: state => (state.themeConfig.isDark || state.themeConfig.headerBgRevert ? '#bdbdc0' : '#303133')
	},
	actions: {
		// setToken
		setToken(token: string) {
			this.token = token
		},
		// setUserInfo
		setUserInfo(userInfo: any) {
			this.userInfo = userInfo
		},
		// setAssemblySizeSize
		setAssemblySizeSize(assemblySize: string) {
			this.assemblySize = assemblySize
		},
		// updateLanguage
		updateLanguage(language: string) {
			this.language = language
		},
		// setThemeConfig
		setThemeConfig(themeConfig: ThemeConfigProps) {
			this.themeConfig = themeConfig
		}
	},
	persist: piniaPersistConfig('GlobalState')
})

// piniaPersist(持久化)
const pinia = createPinia()
const PINIA_BASE_KEY = import.meta.env.VITE_PINIA_BASE_KEY
pinia.use(
	createPersistedState({
		key: id => `${PINIA_BASE_KEY}${id}`
	})
)

export default pinia
